package com.example.recordingpen_datacollection.Utils.http;


import com.alibaba.fastjson.JSON;
import okhttp3.*;
import okhttp3.logging.HttpLoggingInterceptor;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName OkHttpUtils
 * @description: http客户端远程调用通用工具类
 * @author: chenlf
 * @Version 1.0
 **/
public class OkHttpUtils {

    private static HttpLoggingInterceptor logger = new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC);

    private static OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(60, TimeUnit.SECONDS) // 设置连接超时时间为30秒
            .readTimeout(60, TimeUnit.SECONDS) // 设置读取超时时间为60秒
            .writeTimeout(60, TimeUnit.SECONDS) // 设置写入超时时间为60秒
            .addInterceptor(logger)
            .build();

    public static String execute(String url, String method, RequestBody requestBody, Map<String, String> headers){

        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
                .method(method, requestBody);

        if (headers != null && !headers.isEmpty()) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }

        try (Response response = client.newCall(requestBuilder.build()).execute()) {

            if (!response.isSuccessful()){
                throw new IOException("远程调用接口失败：" + response);
            }

            return response.body().string();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public static String doGet(String url){
//        System.out.println(System.currentTimeMillis() +" okHttp");
        return execute(url, "GET", null, null);
    }

    public static String doGet(String url, Map<String, String> headers){
        return execute(url, "GET", null, headers);
    }

    public static String doPost(String url, String jsonBody){
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), JSON.toJSONString(jsonBody));
        return execute(url, "POST", body, null);
    }

    public static String doPost(String url, RequestBody body){
        return execute(url, "POST", body, null);
    }

    public static String doPost(String url, String jsonBody, Map<String, String> headers){
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), JSON.toJSONString(jsonBody));
        return execute(url, "POST", body, headers);
    }
    public static String doPost(String url, RequestBody body, Map<String, String> headers){
        return execute(url, "POST", body, headers);
    }

    public static String doPost2(String url, String json){
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS) // 设置连接超时时间为30秒
                .readTimeout(60, TimeUnit.SECONDS) // 设置读取超时时间为60秒
                .writeTimeout(60, TimeUnit.SECONDS) // 设置写入超时时间为60秒
                .addInterceptor(logger)
                .build();

        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("Authorization", "bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOm51bGwsInNjb3BlIjpbImFsbCJdLCJhcHBJZCI6Inp5N2FUcnFPdTAiLCJjdXN0b21lcklkIjoxNzgyNjY1NzI5OTA1MTM1NjE2LCJleHAiOjE3MTkzNjAxNzEsImp0aSI6ImVkMTUwNjQyLTY1MmEtNDBiMC1iNTI5LTg2MGVjYzBmN2Q2MSIsImNsaWVudF9pZCI6Inp5N2FUcnFPdTAifQ.dk0Tqb_w3oYHn9w2aak5mwokv_E_7VagPoC6BbcvS-KyFC2ddp3Zfuf5dF9QFbFEVo90ziI0CvOCp2fc83c37s84LtmRyBf3bCogXKIQm47WYlqsOwu0fkwsu7Zf188hjPsxlsahqpU2yqJS9HC3Jc4Hu29j2wRXT89J0UqjfxOfpRxoWyu5GBYz8xqRACll2DOsrbzwkChT0XKDENsIaUIHHufAV-mU8zpUUQ47VgfdOxLJ7wTne2NCQe0B2ORRpaXUChAVpLOFtAgYbSP4FTy0SAhvHBT6151FibgdM3WSFkvC9b2TJXyBDGuPmUkdHNAK8K5i-I96ilNyIGXvpA")
                .addHeader("content-type", "application/json")
                .build();

        try {

            Response response = client.newCall(request).execute();
            if (!response.isSuccessful()){
//                System.out.println(response.body().string());
                throw new IOException("远程调用接口失败：" + response);
            }

            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }





}

